<template>
  <div class="dateContent">
    <el-date-picker v-model="time" :type="dateType" range-separator="To" start-placeholder="开始时间" end-placeholder="结束时间" @change="change" />
  </div>
</template>

<script setup>
import { ref, watch, computed, getCurrentInstance } from "vue";
let props = defineProps(["start", "end", "type"]);
const emit = defineEmits(["update:start", "update:end"]);
const { proxy } = getCurrentInstance();

//computed
let dateType = computed(() => {
  return props.type ? props.type : "daterange";
});

let newTime = computed(() => {
  return props.start || props.end;
});

const time = ref((["", ""]));

let change = (e) => {
  if (e == null) {
    emit("update:start", "");
    emit("update:end", "");
  }
  else if (dateType.value == "daterange") {
    emit("update:start", proxy.$utils.dateTimeFormateFn(e[0]));
    emit("update:end", proxy.$utils.dateTimeFormateFn(e[1]));
  } else {
    emit("update:start", proxy.$utils.dateTimeFormateFn(e[0], "all"));
    emit("update:end", proxy.$utils.dateTimeFormateFn(e[1], "all"));
  }
  if (e) {
    time.value = [...e]
  } else {
    time.value = ["", ""]
  }
};

//watch
watch(
  () => newTime.value,
  (newValue, oldValue) => {
    if (newValue) {
      time.value = [new Date(props.start), new Date(props.end)];
    } else {
      time.value = []
    }
  },
  { immediate: true, deep: true }
);
</script>

<style lang="scss" scoped>
.dateContent {
  width: 100%;

  ::v-deep(.el-date-editor) {
    width: 100%;
  }
}
</style>
